<template>
  <a-card :bordered="false" style="height: 100%;">
    <div class="table-operator" style="display: flex; justify-content: space-between;">
      <!-- <a-button v-if="hasPerm('rdrecord32.Add')" type="primary" icon="plus" @click="handleAdd()">新建</a-button> -->
      <a-form layout="inline">
        <a-row>
          <a-col :md="24" :sm="24">
            <a-input
              style="width: 150px;"
              v-model="queryParam.keyword"
              placeholder="请输入购货方名称"
              @keydown.enter="getDataList" />
            <a-select
              style="width: 100px;margin-left: 8px;"
              v-model="selectTime"
              @change="changeTime"
              name="radioGroup"
              :default-value="0">
              <a-select-option :value="index" v-for="(i, index) in ['一个月', '三个月', '六个月', '自定义']" :key="i">
                {{ i }}
              </a-select-option>
            </a-select>
            <a-range-picker style="margin-left: 8px;width: 220px;" :disabled="timeDisabled" v-model="time" />
            <a-button
              style="margin-left: 8px"
              type="primary"
              @click="() => {
                this.pagination.current = 1
                this.getDataList()
              }
              ">查询
            </a-button>
            <a-button @click="repossess">重置
            </a-button>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <div class="table-page-search-wrapper">
      <!-- <a-form layout="inline">
                <a-row :gutter="10">
                    <a-col :md="4" :sm="24">
                        <a-form-item label="查询类别">
                            <a-select allowClear v-model="queryParam.Condition">
                                <a-select-option key="TicketbuyerName">客户</a-select-option>
                                <a-select-option key="cCusCode">品类</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md="4" :sm="24">
                        <a-form-item>
                            <a-input v-model="queryParam.Keyword" placeholder="关键字" @keydown.enter="getDataList" />
                        </a-form-item>
                    </a-col>
                    <a-col :md="6" :sm="24">
                        <a-button type="primary" @click="() => {
                            this.pagination.current = 1
                            this.getDataList()
                        }">查询</a-button>
                        <a-button style="margin-left: 8px" @click="repossess">重置</a-button>
                    </a-col>
                </a-row>
            </a-form> -->

    </div>
    <!-- :expandedRowRender="expandedRowRenderGrandson" -->

    <a-table
      ref="table"
      :scroll="{ y: 530 }"
      :columns="columns"
      :rowKey="(row, index) => row.Id"
      :dataSource="data"
      :pagination="pagination"
      :row-selection="rowSelection"
      :loading="loading"
      @change="handleTableChange"
      :bordered="true"
      size="small">
      <span slot="CreateTime" slot-scope="CreateTime">{{ timeFormat(CreateTime) }}</span>
      <template slot="State" slot-scope="text, record">
        <!-- <a-tag color="blue">{{ text }}</a-tag> -->
        <a-tag :color="record.State === '已开票' ? 'blue' : 'orange'">{{ text }}</a-tag>
        <!-- <a-tag :color="record.State === 'Running'
                ? 'green'
                : record.State === 'Finished'
                    ? 'blue'
                    : record.State === 'Canceled'
                        ? 'orange'
                        : record.State === 'Exceptional'
                            ? 'red'
                            : record.State === 'Suspended'
                                ? 'pink'
                                : record.State === 'Timeout'
                                    ? 'purple'
                                    : 'green'">{{ record.State === 'Running'
                            ? '审批中'
                            : record.State === 'Finished'
                                ? '已完成'
                                : record.State === 'Canceled'
                                    ? '已驳回'
                                    : record.State === 'Exceptional'
                                        ? '异常'
                                        : record.State === 'Suspended'
                                            ? '已停止'
                                            : record.State === 'Timeout'
                                                ? '已超时'
                                                : '审批中' }}</a-tag> -->

      </template>
    </a-table>

  </a-card>
</template>

<script>
import moment from 'moment'
const columns = [
  // { title: '关联单号', dataIndex: 'OutboundOrder' },
  { title: '申请编号', dataIndex: 'Code' },
  { title: '申请日期', dataIndex: 'CreateTime', scopedSlots: { customRender: 'CreateTime' } },
  { title: '购货方', dataIndex: 'TicketbuyerName', align: 'right', width: '200px' },
  { title: '发票代码', dataIndex: 'Invoicecode', align: 'right' },
  { title: '发票号码', dataIndex: 'Invoicenumber', align: 'right' },
  { title: '发票张数', dataIndex: 'InvoiceQuantity', align: 'right' },
  { title: '开票金额', dataIndex: 'InvoiceAmount', align: 'right' },
  { title: '税额', dataIndex: 'InvoiceTaxAmount', align: 'right' },
  { title: '申请人', dataIndex: 'RealName', align: 'right' },
  { title: '状态', dataIndex: 'State', scopedSlots: { customRender: 'State' }, width: '70px' }
]
const columnsSon = [
  { title: '开票日期', dataIndex: 'CreateTime' },

  { title: '开票数量', dataIndex: 'InvoicingQuantity', align: 'right' },
  { title: '金额', dataIndex: 'InventoryAmount', align: 'right' },
  { title: '税额', dataIndex: 'TaxAmount', align: 'right' }

]
const columnsGrandson = [
  { title: '产品名称', dataIndex: 'InvoicingName' },
  { title: '出库数量', dataIndex: 'InvoicingQuantity', align: 'right' },
  { title: '单价', dataIndex: 'InventoryPrice', align: 'right' },
  { title: '开票金额', dataIndex: 'InvoicingAmount', align: 'right' },
  { title: '税额', dataIndex: 'TaxAmount', align: 'right' },
  { title: '对应发票号', dataIndex: 'OutboundOrder' }
]
export default {
  components: {
  },
  mounted () {
    this.time = [this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth(), 1)), this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0))]
    this.getDataList()
  },
  data () {
    return {
      data: [],
      pagination: {
        current: 1,
        pageSize: 25,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['25', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true
      },
      paginationSon: {
        current: 1,
        pageSize: 10000,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['25', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true
      },
      paginationGrandson: {
        current: 1,
        pageSize: 10000,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['25', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true
      },
      filters: {},
      sorter: { field: 'dDate', order: 'desc' },
      loading: false,
      columns,
      columnsSon,
      timeDisabled: true,
      time: [],
      selectTime: 0,
      columnsGrandson,
      queryParam: {
        'Condition': 'TicketbuyerName',
        'Keyword': ''
      },
      dataSon: [{ vouchertypeName: '123' }],
      dataGrandson: [],
      loadingSon: false,
      loadingGrandson: false,
      selectRows: []
    }
  },
  watch: {
    dataSon: {
      deep: true,
      handler () {
        this.$forceUpdate()
      }
    }
  },
  computed: {
    rowSelection () {
      return {
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectRows = selectedRowKeys
        },
        getCheckboxProps: record => ({
          props: {
            disabled: record.Id == null || !record.Id, // Column configuration not to be checked
            name: record.name
          }
        }),
        selectedRowKeys: this.selectRows
      }
    }
  },
  methods: {
    repossess () {
      this.queryParam = {
        'Condition': 'TicketbuyerName',
        'Keyword': ''
      }
      this.changeTime(0)
      this.getDataList()
    },
    changeTime (e) {
      this.timeDisabled = true
      this.selectTime = e
      this.time = []
      switch (e) {
        case 0:
          this.time[0] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth(), 1))
          this.time[1] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0))
          break
        case 1:
          this.time[0] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() - 2, 1))
          this.time[1] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0))
          break
        case 2:
          this.time[0] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() - 5, 1))
          this.time[1] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0))
          break
        case 3:
          this.timeDisabled = false
          break
      }
    },
    // 第二层孙表格
    expandedRowRenderGrandson (record) {
      if (this.dataGrandson[record.Id]) {
        return (
          <a-table
            columns={this.columnsGrandson}
            data-source={this.dataGrandson[record.Id]}
            pagination={false}
            bordered={true}
            loading={this.loadingGrandson}
            v-on:change={() => { console.log(123) }}
          ></a-table>
        )
      }
      this.loadingGrandson = true
      this.$http.post('/InvoiceManagement/Inv_InvoiceApplyMain/GetInvoicingInformation?id=' + record.Id, '').then(res => {
        this.loadingGrandson = false
        this.dataGrandson[record.Id] = res.Data.Details
        this.dataGrandson[record.Id].forEach(item => {
          item.InvoicingAmount = this.$options.filters.NumberFormats(item.InvoicingAmount)
          item.InventoryPrice = this.$options.filters.NumberFormatss(item.InventoryPrice)
          item.TaxAmount = this.$options.filters.NumberFormats(item.TaxAmount)
        })
        this.$forceUpdate()
      }).catch(err => {
        this.$message.error(err)
      })

      return (
        <a-table
          columns={this.columnsGrandson}
          data-source={this.dataGrandson[record.Id]}
          pagination={false}
          bordered={true}
          loading={this.loadingGrandson}
          v-on:change={() => { console.log(123) }}
        ></a-table>
      )
    },
    handleTableChange (pagination, filters, sorter) {
      this.pagination = { ...pagination }
      this.filters = { ...filters }

      this.getDataList()
    },
    getDataList () {
      this.loading = true
      this.$http
        .post('/InvoiceManagement/v_invoicesquery/GetOutboundOrderDataList', {
          PageIndex: this.pagination.current,
          PageRows: this.pagination.pageSize,
          SortField: 'id',
          SortType: 'desc',
          Search: { ...this.queryParam, StartTime: this.time[0] ? this.timeFormat(this.time[0]) : '', EndTime: this.time[1] ? this.timeFormat(this.time[1]) : '' }
        })
        .then(resJson => {
          this.loading = false
          this.data = resJson.Data
          this.data.forEach(item => {
            // item.Invoicenumber = item.Invoicenumber.split(',').length>1?item.Invoicenumber.split(',')[0]+'...':item.Invoicenumber
            // item.HighopeningAmount = this.$options.filters.NumberFormats(item.HighopeningAmount)
            item.InvoiceAmount = this.$options.filters.NumberFormats(item.InvoiceAmount)
            item.InvoiceTaxAmount = this.$options.filters.NumberFormats(item.InvoiceTaxAmount)
          })
          this.dataSon = []
          this.dataGrandson = []
          if (this.data) {
            const pagination = { ...this.pagination }
            pagination.total = resJson.Total
            this.pagination = pagination
          }
        }).catch(err => {
          this.$message.error(err)
        })
    },
    timeFormat (val) {
      // 时间格式化函数
      return moment(val).format('YYYY-MM-DD')
    },
    openForm () {
      this.selectRows = []
      this.time = [this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth(), 1)), this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0))]
      this.pagination.current = 1
      this.getDataList()
    }
  }
}
</script>
<style scoped>
/deep/ .ant-table-thead>tr>th {
    background: #fff;
}

.grandson td {
    padding: 8px;
}

/deep/ .ant-table-expanded-row .ant-table-expanded-row-level-1>td {
    padding: 8px;
}
</style>
